package com.zhkjnet.zhyy.service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhkjnet.zhyy.ZhyyConfiguration;
import com.zhkjnet.zhyy.bean.JsonResponse;
import com.zhkjnet.zhyy.dao.AssetDao;
import com.zhkjnet.zhyy.dao.MoneyRecordDao;
import com.zhkjnet.zhyy.dao.OilCardDao;
import com.zhkjnet.zhyy.dao.OilRechargeDao;
import com.zhkjnet.zhyy.dao.UserDao;
import com.zhkjnet.zhyy.entity.Asset;
import com.zhkjnet.zhyy.entity.MoneyRecord;
import com.zhkjnet.zhyy.entity.MoneyRecordType;
import com.zhkjnet.zhyy.entity.OilCard;
import com.zhkjnet.zhyy.entity.OilCardType;
import com.zhkjnet.zhyy.entity.OilRecharge;
import com.zhkjnet.zhyy.entity.RechargeStatus;
import com.zhkjnet.zhyy.entity.User;
import com.zhkjnet.zhyy.util.HttpUtil;
import com.zhkjnet.zhyy.util.RechargeOrderId;
import com.zhkjnet.zhyy.util.ZhApi;

@Service
public class OilRechargeService {

    @Autowired
    private OilRechargeDao rechargeDao;

    @Autowired
    private AssetDao assetDao;

    @Autowired
    private MoneyRecordDao moneyRecordDao;

    @Autowired
    private OilCardDao oilCardDao;

    @Autowired
    private ZhyyConfiguration configuration;
    
    @Autowired
    private UserDao userDao;

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private final static Logger logger = LoggerFactory.getLogger(OilRechargeService.class);

    @Transactional
    public boolean save(OilRecharge recharge, Asset asset, User user) {
        boolean apiResult = false;
        OilCard card = oilCardDao.findById(recharge.getCard().getId());
        recharge.setStatus(RechargeStatus.Submit);
        recharge.setCreateTime(new Date());
        try {
        	//获取订单id
        	String orderId = RechargeOrderId.getOrderIdBigCustomer("ZHYBC"+user.getId());
            recharge.setOrderNo(orderId);
            apiResult = true;
            recharge.setApiResult(true);
            //保存油卡充值
            rechargeDao.save(recharge);
            /*Map<String, Object> map = objectMapper.readValue(result, Map.class);
            String code = (String) map.get("code");
            Map<String, Object> data = (Map) map.get("data");
            if (code.equals("0")) {
                //调用接口失败
                apiResult = false;
                recharge.setApiResult(false);
                recharge.setStatus(RechargeStatus.Fail);
                apiResult = false;
                logger.error("oil recharge result error : " + result);
                logger.error("oil recharge err obj : " + objectMapper.writeValueAsString(params));
            } else if (code.equals("1")) {
                
            }
            */
            //成功才扣款
            if (apiResult) {
                //扣除可用余额
                asset.setAbleMoney(asset.getAbleMoney() - recharge.getMoney());
                assetDao.update(asset);
                //记录
                MoneyRecord moneyRecord = new MoneyRecord();
                moneyRecord.setMessage("油卡充值");
                moneyRecord.setMoney(- recharge.getMoney());
                moneyRecord.setUser(user);
                moneyRecord.setType(MoneyRecordType.Able);
                moneyRecordDao.save(moneyRecord);
                //添加使用次数
                card.setDayTimes(card.getDayTimes() + 1);
                oilCardDao.update(card);
            }
            String params = ZhApi.sign2(
                    configuration.getZh().getAppKey(),
                    configuration.getZh().getAppSecret(),
                    card.getNumber(),
                    card.getUsername(),
                    card.getPhone(),
                    recharge.getMoney() / 100,
                    orderId);
            HttpUtil.post(configuration.getZh().getHost() + "/recharge/api2?" + params, "");
            
        } catch (IOException e) {
            recharge.setApiResult(false);
            e.printStackTrace();
        }
        
        
        return apiResult;
    }

    @Transactional
    public void update(OilRecharge recharge) {
        rechargeDao.update(recharge);
    }

    public List<OilRecharge> findAll(Long page, Integer length) {
        return rechargeDao.findAll((page - 1) * length, length);
    }

    public Long count() {
        return rechargeDao.count();
    }

    public List<OilRecharge> findAllByCardId(Long id) {
        return rechargeDao.findAllByCardId(id);
    }

    public List<OilRecharge> findAllByUserId(Long userId, Long offset, Integer count) {
        return rechargeDao.findAllByUserId(userId, offset, count);
    }

    public List<OilRecharge> findAllResult(Integer min) {
        Date now = new Date();
        Date time = new Date(now.getTime() - min * 60 * 1000);
        return rechargeDao.findAllResult(time);
    }

    /**
     * 批量充油
     * @param requeset
     * @param response
     * @param gasType
     * @param cards
     * @param prices
     * @return
     */
    @Transactional
	public JsonResponse oilRechargeBatch(HttpServletRequest request,HttpServletResponse response,String cardType, String cards, Long prices) {
    	
    	logger.info("cards="+cards+",prices="+prices+",cardType="+cardType);
    	JsonResponse json = new JsonResponse();
		OilCardType type = null;
		if(cardType.equals("cnpc")){
			type = OilCardType.ZSY;
		}
		if(cardType.equals("sinopec")){
			type = OilCardType.ZSH;
		}
		// 查询用户
		Long userId = (Long)request.getSession().getAttribute("id");
		User currentUser = userDao.findById(userId);
		String[] cardsArray = cards.split(",");
		int num = cardsArray.length;
		Long totalPrice = num * (prices*100);
		logger.info("当前的充值数据:"+Arrays.deepToString(cardsArray)+",totalPrice="+totalPrice);
		
		// 获取用户余额
		Asset asset = assetDao.findByUserId(userId);
		logger.info("ableMoney="+asset.getAbleMoney()+",");
		if(asset.getAbleMoney() < totalPrice){
			return JsonResponse.error(0,"可用余额不足");			
		}else{
			try {
				//扣除可用余额
				asset.setAbleMoney(asset.getAbleMoney() - prices*100);
				//扣钱
				assetDao.update(asset);
				for (String cardNo : cardsArray) {
					
		            	
					OilRecharge oilRecharge = new OilRecharge();
					oilRecharge.setStatus(RechargeStatus.Submit);
					oilRecharge.setCreateTime(new Date());
					oilRecharge.setMoney(prices*100);
					oilRecharge.setCardNo(cardNo);
					oilRecharge.setUserId(userId);
					
		        	//获取订单id
		        	String orderId = RechargeOrderId.getOrderIdBigCustomer("ZHYBC"+currentUser.getId());
		        	oilRecharge.setOrderNo(orderId);
		            oilRecharge.setApiResult(true);
		            //保存油卡充值
		            int save = rechargeDao.save(oilRecharge);
		            
		            //记录
	                MoneyRecord moneyRecord = new MoneyRecord();
	                moneyRecord.setMessage("油卡充值");
	                moneyRecord.setMoney(- oilRecharge.getMoney());
	                moneyRecord.setUser(currentUser);
	                moneyRecord.setType(MoneyRecordType.Able);
	                moneyRecordDao.save(moneyRecord);
	                
	                
	                logger.info("大客户，开始发送充油动作....");
	                String params = ZhApi.sign2(
	                        configuration.getZh().getAppKey(),
	                        configuration.getZh().getAppSecret(),
	                        oilRecharge.getCardNo(),
	                        currentUser.getNickname(),
	                        currentUser.getPhone(),
	                        oilRecharge.getMoney() / 100,
	                        orderId);
	                HttpUtil.post(configuration.getZh().getHost() + "/recharge/api2?" + params, "");
			           
	                
					
				}
			} catch (Exception e) {
	        	json.setCode(-1);
	        	json.setMessage("系统繁忙,请稍后再试!");
	            e.printStackTrace();
	            return json;
	        }
		}
		json.setCode(1);
		json.setMessage("提交成功,正在为您充值!");
		return json;
	}
    
    public synchronized boolean save_oil(OilRecharge recharge, Asset asset, User user) {
        boolean apiResult = false;
        //OilCard card = oilCardDao.findById(recharge.getCard().getId());
        recharge.setStatus(RechargeStatus.Submit);
        recharge.setCreateTime(new Date());
        try {
        	//获取订单id
        	String orderId = RechargeOrderId.getOrderIdBigCustomer("ZHYBC"+user.getId());
            recharge.setOrderNo(orderId);
            apiResult = true;
            recharge.setApiResult(true);
            //保存油卡充值
            rechargeDao.save(recharge);
            //成功才扣款
            if (apiResult) {
               
                
                /*//添加使用次数
                card.setDayTimes(card.getDayTimes() + 1);
                oilCardDao.update(card);*/
            }
            
            logger.info("大客户，开始发送充油动作....");
            String params = ZhApi.sign2(
                    configuration.getZh().getAppKey(),
                    configuration.getZh().getAppSecret(),
                    recharge.getCardNo(),
                    user.getNickname(),
                    user.getPhone(),
                    recharge.getMoney() / 100,
                    orderId);
            HttpUtil.post(configuration.getZh().getHost() + "/recharge/api2?" + params, "");
            
        } catch (IOException e) {
            recharge.setApiResult(false);
            e.printStackTrace();
        }
        
        
        return apiResult;
    }
    
    @Transactional
	public JsonResponse oilRechargeBatch_backup(HttpServletRequest request,HttpServletResponse response,String cardType, String cards, Long prices) {
    	
    	logger.info("cards="+cards+",prices="+prices+",cardType="+cardType);
    	JsonResponse json = new JsonResponse();
		OilCardType type = null;
		if(cardType.equals("cnpc")){
			type = OilCardType.ZSY;
		}
		if(cardType.equals("sinopec")){
			type = OilCardType.ZSH;
		}
		
		
		// 查询用户
		Long userId = (Long)request.getSession().getAttribute("id");
		User user = new User();
		user.setId(userId);
		User currentUser = userDao.findById(userId);
		String[] cardsArray = cards.split(",");
		int num = cardsArray.length;
		Long totalPrice = num * prices;
		logger.info("当前的充值数据:"+cardsArray.toString()+",totalPrice="+totalPrice);
		
		// 获取用户余额
		Asset asset = assetDao.findByUserId(userId);
		logger.info("ableMoney="+asset.getAbleMoney()+",");
		if(asset.getAbleMoney() < totalPrice){
			return JsonResponse.error(0,"可用余额不足");			
		}else{
			for (String cardNo : cardsArray) {
				boolean apiResult = false;
				OilRecharge oilRecharge = new OilRecharge();
				oilRecharge.setStatus(RechargeStatus.Submit);
				oilRecharge.setCreateTime(new Date());
				oilRecharge.setMoney(prices*100);
				oilRecharge.setCardNo(cardNo);
				oilRecharge.setUserId(userId);
				try {
		            String params = ZhApi.sign(
		                    configuration.getZh().getAppKey(),
		                    configuration.getZh().getAppSecret(),
		                    cardNo,
		                    currentUser.getNickname(),
		                    currentUser.getPhone(),
		                    prices,
		                    type);
		            String result = HttpUtil.post(configuration.getZh().getHost() + "/recharge/api?" + params, "");
		            Map<String, Object> map = objectMapper.readValue(result, Map.class);
		            String code = (String) map.get("code");
		            Map<String, Object> data = (Map) map.get("data");
		            if (code.equals("0")) {
		            	
						//调用接口失败
						oilRecharge.setApiResult(false);
						oilRecharge.setStatus(RechargeStatus.Fail);
						apiResult = false;
						logger.error("oil recharge result error : " + result);
						logger.error("oil recharge err obj : " + objectMapper.writeValueAsString(params));
		            } else if (code.equals("1")) {
		                apiResult = true;
		                oilRecharge.setOrderNo((String) data.get("orderNo"));
		                oilRecharge.setApiResult(true);
		            }
		            // 保存充值记录
		            rechargeDao.save(oilRecharge);
		            //成功才扣款
			        if (apiResult) {
			            //扣除可用余额
			            asset.setAbleMoney(asset.getAbleMoney() - prices*100);
			            assetDao.update(asset);
			            //记录
			            MoneyRecord moneyRecord = new MoneyRecord();
			            moneyRecord.setMessage("油卡充值");
			            moneyRecord.setMoney(- prices*100);
			            moneyRecord.setUser(user);
			            moneyRecord.setType(MoneyRecordType.Able);
			            moneyRecordDao.save(moneyRecord);
			        }
		        } catch (IOException e) {
		        	json.setCode(-1);
		        	json.setMessage("系统繁忙,请稍后再试!");
		            e.printStackTrace();
		            return json;
		        }
			}
		}
		json.setCode(1);
		json.setMessage("提交成功,正在为您充值!");
		return json;
	}

}
